/*
 * Copyright 2009-2019 the original author or authors  
 *
 */
package com.livery.liu.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;


/**
 *
 * <p></p>
 * <pre class="code">
 *  
 * </pre>
 *
 * @author  <a href="mailto:livery.liu@gmail.com"> livery liu</a>
 */

public class ConnectionUtil {
	private static DataSource dataSource = null;
	private ConnectionUtil() {
		
	}
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Properties prop = new Properties();
			InputStream is = ConnectionUtil.class.getClassLoader().getResourceAsStream("datasource.properties");
			prop.load(is);
			dataSource = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static DataSource getDataSource() {
		return dataSource;
	}

	public static Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}

	/**
	 * 释放rs、statement、connection
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
		}
	}
}
